package com.illtamer.infinite.collapsar.common.dao;

import com.illtamer.infinite.collapsar.common.MySQLConfig;
import com.illtamer.infinite.collapsar.common.entity.Email;
import lombok.SneakyThrows;

import javax.sql.DataSource;
import java.sql.*;

public class EmailDao {

    private static final String INSERT = "INSERT INTO " + MySQLConfig.EMAIL_TABLE + "(subject, `from`, sender, replyTo, `to`, cc, bcc, comments, keywords, inReplyTo, `references`, encrypted, date, `content`) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    private final DataSource dataSource;

    public EmailDao(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @SneakyThrows(SQLException.class)
    public Email insert(Email email) {
        try (Connection connection = dataSource.getConnection()) {
            PreparedStatement ps = connection.prepareStatement(INSERT, Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, email.getSubject());
            ps.setString(2, email.getFrom());
            ps.setString(3, email.getSender());
            ps.setString(4, email.getReplyTo());
            ps.setString(5, email.getTo());
            ps.setString(6, email.getCc());
            ps.setString(7, email.getBcc());
            ps.setString(8, email.getComments());
            ps.setString(9, email.getKeywords());
            ps.setInt(10, email.getInReplyTo());
            ps.setInt(11, email.getReferences());
            ps.setString(12, email.getEncrypted());
            ps.setTimestamp(13, new Timestamp(email.getDate().getTime()));
            ps.setString(14, email.getContent().saveToString());
            ps.executeUpdate();
            final ResultSet resultSet = ps.getGeneratedKeys();
            while (resultSet.next())
                email.setId(resultSet.getInt(1));
        }
        return email;
    }

}
